var vueData = {
  isShow: false,
  loading: false,
  persons: null,
  mode: '',
  selectData: null,
  leaderId: [],
  attendance: {
    depts: [],
    persons: []
  }
};
var app = new Vue({
  el: '#vueApp',
  data: vueData,
  watch: {
    isShow: function () {
      var isShow = this.isShow;
      if (isShow) {
        var mode = this.mode;
        if (mode === 'attendance') {
          this.selectData = this.attendance;
        } else if (mode === 'leader') {
          this.selectData = this.leaderId;
        }
        if (this.persons === null) {
          this.setPersons();
        }
      } else {
        this.mode = '';
      }
    }
  },
  methods: {
    setPersons: function () {
      this.loading = true;
      var self = this;
      ajaxRequest('dingTalk/getParticipantInfo').then(function (persons) {
        self.persons = persons;
        self.loading = false;
      }).catch(function () {
        self.loading = false;
      });
    },

    closeModal: function () {
      $('#participantModal').modal('hide');
    },

    ensure: function () {
      var data = this.$refs['peopleSelect'].getData();
      var mode = this.mode;
      if (mode === 'leader') {
        this.setLeaderData(data);
      } else if (mode === 'attendance') {
        this.setAttendanceData(data);
      }
      $('#participantModal').modal('hide');
    },

    setLeaderData: function (data) {
      var leaderId = _.map(data, 'id');
      this.leaderId = leaderId;
      $("#leaderBtn").text(leaderId.length + "人");
    },

    setAttendanceData: function (data) {
      var depts = data.depts;
      var deptIds = [];
      var $participantDiv = $('#participant .participantDiv');
      if ($participantDiv.length === 0) {
        $participantDiv = $('<div class="participantDiv"></div>');
        $("#participant").append($participantDiv);
      } else {
        $participantDiv.html('');
      }

      for (var i = 0; i < depts.length; i++) {
        var dept = depts[i];
        deptIds.push(dept.id);

        var $participantItem = $('<span class="participantItem"></span>');
        $participantItem.html(dept.name);
        $participantDiv.append($participantItem);
      }
      this.attendance.depts = deptIds;

      var persons = data.persons;
      var personIds = [];
      for (var i = 0; i < persons.length; i++) {
        var person = persons[i];
        personIds.push(person.id);

        var $participantItem = $('<span class="participantItem"></span>');
        $participantItem.html(person.name);
        $participantDiv.append($participantItem);
      }
      this.attendance.persons = personIds;

      if (depts.length === 0 && persons.length === 0) {
        $("#participantBtn").show();
        $participantDiv.remove();
      } else {
        $("#participantBtn").hide();
      }
    }
  },
  components: {
    DeptTransfer: DeptTransfer
  }
});

$(function () {
	queryClass();
	queryOvertimeRule();
	page.bind();
	changeClass();
	var a = GetRequest();
	var index_1 = a['value']; //考勤组id
	if (index_1 != undefined && index_1 != "") {
		//设置保存按钮的value
	    $("#save").val(index_1);
	    //根据传递来的参数查询考勤组信息
	    ajaxUtil.ajaxRuquest("dingTalk/getGroupDetail", {
	    	"id": index_1
	    },
	      function (data) {
	        var detail = data[0];
	        $("#groupName").val(detail.groupName);
	        $("[name='radio']").eq(detail.attendanceType).attr("checked", true);
	        var monday = detail.monday;
	        monday = monday == null ? '' : monday.split(",");
	        var tuesday = detail.tuesday;
	        tuesday = tuesday == null ? '' : tuesday.split(",");
	        var wednesday = detail.wednesday;
	        wednesday = wednesday == null ? '' : wednesday.split(",");
	        var thursday = detail.thursday;
	        thursday = thursday == null ? '' : thursday.split(",");
	        var friday = detail.friday;
	        friday = friday == null ? '' : friday.split(",");
	        var saturday = detail.saturday;
	        saturday = saturday == null ? '' : saturday.split(",");
	        var sunday = detail.sunday;
	        sunday = sunday == null ? '' : sunday.split(",");
	        var week = [monday, tuesday, wednesday, thursday, friday, saturday, sunday];
	        var weeks = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
	        for (var i = 0; i < 7; i++) {
	          if (week[i][1] != "") {
	            $("input:checkbox[value='" + weeks[i] + "']").attr("checked", true);
	            $("#" + weeks[i]).text(week[i][0]);
	            $("#" + weeks[i]).attr("value", week[i][1]);
	          }
	        }
	        //参与人员
	        var deptList = detail.deptList;
	        var deptIds = _.map(deptList, 'deptId');
	        var deptNames = _.map(deptList, 'deptName');
	        vueData.attendance.depts = deptIds;
	
	        var userList = detail.userList;
	        var personIds = _.map(userList, 'userId');
	        var personNames = _.map(userList, 'userName');
	        vueData.attendance.persons = personIds;
	
	        var participantList = _.concat(deptNames, personNames);
	        var html = "<div class='participantDiv'>";
	        for (var i = 0, len = participantList.length; i < len; i++) {
	          if (participantList[i] != "") {
	            html += "<span class='participantItem'>" + participantList[i] + "</span>";
	          }
	        }
	        html += "</div>";
	        $("#participantBtn").hide();
	        $("#participant").append(html);
	        //负责人
	        var leaderList = detail.leaderList;
	        var leaderIds = _.map(leaderList, 'leaderId');
	        var leaderNames = _.map(leaderList, 'leaderName');
	        vueData.leaderId = leaderIds;
	        $("#leaderBtn").text(leaderNames.length + "人");
	        $("#punchInAlert").val(detail.punchInMintues);
	        $("#punchOutAlert").val(detail.punchOutMintues);
	        $("#overtimeRuleId").val(detail.overtimeRuleId);
	        $("#ruleNameSpan").text(detail.overtimeRuleContent==null?"未设置":detail.overtimeRuleContent);
      });
  }
})
function monthlyPlanShow(year,month){
	ajaxUtil.ajaxRequest("dingTalk/getGroupMonthlyPlan",{groupId:$("#save").val(),date:year+"-"+month+"-01"})
	.then(function(res){
		$("#monthlyClassSetTable tbody").html("");
		var html = "";
		var length = res.length;
		if(length>0){
			for(var i=0;i<length;i++){
				var temp = i+1;
				html += "<tr><td><input name='check' type='checkbox' /></td><td>"+res[i].workdate+"</td><td>"+res[i].description+"</td><td><a value='"+temp+"' data_value='"+res[i].classId+"' name='edit' style='font-size: 12px;margin-left: 10px;color: #38adff;background: transparent;text-decoration: none;outline: none;cursor: pointer;'>更改班次</a></td></tr>";
			}
		}else{
			var maxDays = new Date(year,month,0).getDate();
			for(var i = 1;i <= maxDays;i++) {
				var t = i>=10?i:"0"+i;
				html += "<tr><td><input name='check' type='checkbox' /></td><td>"+year+"-"+month+"-"+t+"</td><td>休息</td><td><a value='"+i+"' data_value='-1' name='edit' style='font-size: 12px;margin-left: 10px;color: #38adff;background: transparent;text-decoration: none;outline: none;cursor: pointer;'>更改班次</a></td></tr>";
			}
		}
		$("#monthlyClassSetTable tbody").html(html);
		$("#monthlyClassSetDiv").show();
	});
}
function dateChanged(){
	var yyyy = $dp.cal.newdate.y;
	var MM = $dp.cal.newdate.M>=10?$dp.cal.newdate.M:"0"+$dp.cal.newdate.M
	monthlyPlanShow(yyyy,MM);
}
var page = {
  bind: function () {
	  //选择加班规则模态框中点击确认 修改加班规则
	  $("#overtimeRuleConfirm").bind("click",function(){
		  var element = $("#selectOvertimeRuleTable tbody input[name='overtimeRuleRadio']:checked");
		  var value = element.val();
		  if(value===undefined){
			  layAlert("请选择加班规则");
			  return;
		  }
		  var ruleName = element.parent().next().text();
		  $("#changeOvertimeRule").val(value);
		  $("#ruleNameSpan").text(ruleName);
		  $("#overtimeRuleModal").modal("hide");
	  });
	  //点击更改 打开选择加班规则模态框
	  $("#changeOvertimeRule").bind("click",function(){
		  $("#overtimeRuleModal").modal("show");
	  });
	  //点击按月排班的全选按钮
	  $("#monthlyClassSetTable").on("click","input[name='checkAll']",function(){
		  if (this.checked) {
			  //trigger触发"change"事件
			  $("#monthlyClassSetTable tbody input[name='check']").prop("checked", true).trigger("change");
		  } else {
			  $("#monthlyClassSetTable tbody input[name='check']").prop("checked", false).trigger("change");
		  }
	  });
	  //按月排班的checkbox点击事件
	  $("#monthlyClassSetTable tbody").on("change","input[name='check']",function(){
		  var value = $("#monthlyClassSetDiv div a[name='edit']").attr("value");
		  var text = $("#monthlycheckQucik").text();
		  if(this.checked){
			  $(this).parent().siblings().find("a[name='edit']").attr("data_value",value);
			  $(this).parent().parent().find("td:eq(2)").text(text);
		  }else{
			  $(this).parent().siblings().find("a[name='edit']").attr("data_value","-1");
			  $(this).parent().parent().find("td:eq(2)").text("休息");
		  }
	  });
	  $("#monthlyClassSetDiv").on("click","a[name='edit']",function(){
		  var value = $(this).attr("value");
	      $("#confirm").val(value);
	      $("#selectClassModal").modal("show");
	  });
		//是否手动排班
		$("#manualPlan").bind("change",function(){
			if(this.checked){
				$("#datePickDiv").show();
				var currentDate = new Date();
				var year = currentDate.getFullYear();
				var month = currentDate.getMonth()+1;
				monthlyPlanShow(year,month);
				$("#datePick").val(year+"-"+month);
			}else{
				$("#datePickDiv").hide();
				$("#monthlyClassSetDiv").hide();
			}
		});
		//点击保存按钮时
		$("#save").bind("click", function () {
		  var id = $(this).val();
		  var name = $("#groupName").val();
		  if (name == "" || name.length <= 0) {
		    layAlert("考勤组名称不能为空");
		    return false;
		  }
	      //考勤组成员
	      var attendance = vueData.attendance;
	      var depts = attendance.depts;
	      var deptMember = depts.join(',');
	      var persons = attendance.persons;
	      var userMember = persons.join(',');
	      //考勤组负责人
	      var leaderId = vueData.leaderId;
	      var leader = leaderId.join(',');
	      //考勤类型
	      var radio = $("[name='radio']");
	      var type;
	      for (var i = 0, len = radio.length; i < len; i++) {
	        if (radio[i].checked) {
	          type = i;
	        }
	      }
	      var monday = $("#monday").attr("value");
	      var tuesday = $("#tuesday").attr("value");
	      var wednesday = $("#wednesday").attr("value");
	      var thursday = $("#thursday").attr("value");
	      var friday = $("#friday").attr("value");
	      var saturday = $("#saturday").attr("value");
	      var sunday = $("#sunday").attr("value");
	      var compareArr = [];
	      monday = monday == undefined ? '' : monday;compareArr.push(monday);
	      tuesday = tuesday == undefined ? '' : tuesday;compareArr.push(tuesday);
	      wednesday = wednesday == undefined ? '' : wednesday;compareArr.push(wednesday);
	      thursday = thursday == undefined ? '' : thursday;compareArr.push(thursday);
	      friday = friday == undefined ? '' : friday;compareArr.push(friday);
	      saturday = saturday == undefined ? '' : saturday;compareArr.push(saturday);
	      sunday = sunday == undefined ? '' : sunday;compareArr.push(sunday);
	      var temp = "";
	      for (var i = 0; i < compareArr.length; i++) {
	    	  if(temp=="" && compareArr[i]!=""){
	    		  temp = compareArr[i];
	    	  } 
	    	  if(compareArr[i]!='' && compareArr[i]!=temp){
	    		  layAlert("除休息外一个考勤组只能设置一种班次");
	    		  return false;
	    	  }
	      }
	      var monthlyClassArray = [];
	      if(document.getElementById("manualPlan").checked){
	    	  $("#monthlyClassSetTable tbody a[name='edit']").each(function(){
	    		  monthlyClassArray.push({workdate:$(this).parent().parent().find("td:eq(1)").text(),classId:$(this).attr("data_value")});
	    	  });
	      }
	      var overtimeRuleId = $("#changeOvertimeRule").val();
	      var overtimeRuleContent = $("#ruleNameSpan").text();
	      var url = "";
	      if ($(this).val()!=undefined && $(this).val()!="") {
	        //update
	        url = "dingTalk/updateGroup";
	      } else {
	        //insert
	        url = "dingTalk/insertGroup";
	      }
	      ajaxUtil.ajaxRuquest(url, {
	          "id": id,
	          "groupName": name,
	          "deptMember": deptMember,
	          "personMember": userMember,
	          "leader": leader,
	          "attendanceType": type,
	          "monday": monday,
	          "tuesday": tuesday,
	          "wednesday": wednesday,
	          "thursday": thursday,
	          "friday": friday,
	          "saturday": saturday,
	          "sunday": sunday,
	          "punchInMinutes":$("#punchInAlert").val(),
	          "punchOutMinutes":$("#punchOutAlert").val(),
	          'monthlyClassArray':JSON.stringify(monthlyClassArray),
	          'overtimeRuleId':overtimeRuleId,
	          'overtimeRuleContent':overtimeRuleContent
	        },
	        function (data) {
	          window.history.back();
	        });
    });
	//点击更改加班规则后，打开选择加班规则模态框
	$("#overtimeRuleModal").on("shown.bs.modal", function () {
		ajaxUtil.dataTablesJavascriptSourcedData("selectOvertimeRuleTable",10,dataSet,
				[
					{"data":"id",render:function(data){
						return "<input type='radio' name='overtimeRuleRadio' value='"+data+"'/>";
					}},
					{"data":"ruleName"},
					{"data":"content"}
				]);
    });
	//点击更改班次后，打开选择班次模态框
	$("#selectClassModal").on("shown.bs.modal", function () {
		ajaxUtil.dataTablesJavascriptSourcedData("selectClassTable",10,classDataSet,
				[
					{"data":"id",render:function(data){
						 return "<input type='radio' name='radio1' value='" + data + "'>";
					}},
					{"data":"className"},
					{"data":"attendanceTime"}
				]);
    });
    //模态框显示后
    $("#participantModal").on("shown.bs.modal", function () {
      vueData.isShow = true;
    });
    //选择部门与人员模态框隐藏时
    $("#participantModal").on("hide.bs.modal", function () {
      //选择部门与人员模态框隐藏后
      vueData.isShow = false;
    });
    //点击参与人员按钮时
    $("#participant").bind("click", function () {
      vueData.mode = 'attendance';
      $("#participantModal").modal("show");
    })
    //点击负责人按钮时
    $("#leader").bind("click", function () {
      vueData.mode = 'leader';
      $("#participantModal").modal("show");
    })
    //更改班次按钮
    $(".selectClass").bind("click", function () {
      var value = $(this).attr("value");
      $("#confirm").val(value);
      $("#selectClassModal").modal("show");
    });
    //点击选择班次模态框的确认按钮时
    $("#confirm").bind("click", function () {
      var value = $(this).attr("value"); //确认按钮的value
      var ival = parseInt(value);
      //获取班次信息数据，根据确认按钮的value值进行更改，当value为空时全部更改
      $("#selectClassTable :checked").each(function () {
        var id = $(this).val();
        var name = $(this).parents().children('td').eq(1).text();
        var time = $(this).parents().children('td').eq(2).text();
        var asd = name + ": " + time;
        if(isNaN(ival)){
        	if (value == "") {
        		$("#quickClass").attr("value", id);
        		$("#quickClass").text(asd);
        		$("#selectAll").removeAttr("disabled");
        	} else {
        		$("#" + value).attr("value", id);
        		$("#" + value).text(asd);
        	} 
        }else{
        	if(value==-1){
        		$("#monthlyClassSetDiv div a[name='edit']").attr("value", id);
        		$("#monthlycheckQucik").text(asd);
        		$("#monthlycheckAll").removeAttr("disabled");
        	}else{
        		var value_1 = value-1;
        		var element = $("#monthlyClassSetTable tbody a[name='edit']:eq("+value_1+")");
        		element.attr("data_value",id);
        		element.parent().prev().text(asd);
        	}
        }
      })
      $('#selectClassModal').modal('hide');
    });
  },
}
var arr = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
//点击班次复选框按钮时
function changeClass() {
  $("input[name='mychk']").each(function (i) {
    $(this).click(function () {
      var id = this.value;
      if (id != "") { //点击的不是全选按钮
        if (this.checked == true) { //选中后改变班次时间段的文本
          var quickClass = $("#quickClass").text();
          var quickClassValue = $("#quickClass").attr("value");
          $("#" + id).text(quickClass);
          $("#" + id).attr("value", quickClassValue);
        } else { //取消选中后变为休息
          $("#" + id).text("休息");
          $("#" + id).attr("value", "");
        }
      } else { //点击的是全选按钮
        if (this.checked == true) { //选中全选按钮后
          var quickClass = $("#quickClass").text();
          var quickClassValue = $("#quickClass").attr("value");
          $("input[name='mychk']").each(function (i) {
            $("#" + arr[i]).text(quickClass);
            $("#" + arr[i]).attr("value", quickClassValue);
          })
        } else { //取消全选按钮后
          $("input[name='mychk']").each(function (i) {
            $("#" + arr[i]).text("休息");
            $("#" + arr[i]).attr("value", "");
          })
        }
      }
    })
  })
}
var classDataSet
function queryClass(){
	new Promise(function (resole, reject) {
        $.ajax({
            url: "dingTalk/queryClass",
            type: 'POST',
            data: {},
            dataType: 'json',
            success: function (res) {
                if (!res) {
                	layAlert(res.info);
                    reject();
                    return;
                }
                classDataSet = res.returnData;
            }
        });
    });
}
var dataTable;
var dataSet;
function queryOvertimeRule(){
	new Promise(function (resole, reject) {
        $.ajax({
            url: "dingTalk/queryAttendOvertimeRule",
            type: 'POST',
            data: {},
            dataType: 'json',
            success: function (res) {
                if (!res) {
                	layAlert(res.info);
                    reject();
                    return;
                }
                dataSet = res.returnData;
            }
        });
    });
}
//获取请求参数
function GetRequest() {
  var url = location.search; //获取url中"?"符后的字串
  var theRequest = new Object();
  if (url.indexOf("?") != -1) {
    var str = url.substr(1);
    strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
    }
  }
  return theRequest;
}